package com.ujiuye.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.ArrayList;
import java.util.List;
@WebListener
public class LoginListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {

    ServletContext sc=null;
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
      //ServletContext对象创建时，需要在里面放一个容器，用于存放登录的用户名
        List<String> list = new ArrayList<>();
        sc = servletContextEvent.getServletContext();
        sc.setAttribute("list",list);
    }
    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        //用户登录成功，将用户名放入Session的同时，还要将用户名放到ServletContent对象的容器中
        //获取当前监听到放到Session中的数据
        //放到session中的数据key为username
        //se.getName()获取当前监听到的放到Session中的数据的key
        //se.getValue()获取当前监听到的放到Session中的数据的value
        if ("username".equals(httpSessionBindingEvent.getName())) {
            String username = (String)httpSessionBindingEvent.getValue();
            List<String> list = (List<String>)sc.getAttribute("list");
            list.add(username);
            //将更新以后的容器再放回ServletContent对象
            sc.setAttribute("list",list);
        }
    }
        @Override
        public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
          //用户退出登录时，需要将该用户名从ServletContent对象的容器中移除
            List<String> list = (List<String>)sc.getAttribute("list");
            //获取当前退出的登录名
            String username = (String)httpSessionEvent.getSession().getAttribute("username");
            //移除
            list.remove(username);
            //将更新以后的容器再放回SercletContent对象
            sc.setAttribute("list",list);

        }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

    }

}
